#include <func.h>
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 3);
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    ERROR_CHECK(sfd, -1, "socket")
    struct sockaddr_in ser_addr;
    bzero(&ser_addr, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_port = htons(atoi(argv[2]));
    int ret = bind(sfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
    ERROR_CHECK(ret, -1, "bind")
    char buf[128] = {0};
    struct sockaddr_in client_addr;
    bzero(&client_addr, sizeof(client_addr));
    socklen_t addr_len = sizeof(client_addr);
    ret = recvfrom(sfd, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &addr_len);
    printf("client ip=%s,port=%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
    fd_set rdset;
    while (1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(sfd, &rdset);
        ret = select(sfd + 1, &rdset, NULL, NULL, NULL);
        if (FD_ISSET(STDIN_FILENO, &rdset))
        {
            bzero(buf, sizeof(buf));
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            ERROR_CHECK(ret, -1, "read")
            sendto(sfd, buf, strlen(buf)-1, 0, (struct sockaddr *)&client_addr, sizeof(client_addr));
        }
        if (FD_ISSET(sfd, &rdset))
        {
            bzero(buf, sizeof(buf));
            ret = recvfrom(sfd, buf, sizeof(buf), 0,(struct sockaddr *)&client_addr, &addr_len);
            printf("%s\n", buf);
        }

        
    }
    close(sfd);
        return 0;
}